import { root } from './store';
import  ReactDOMServer  from 'react-dom/server';
import { Provider } from 'react-redux';
import { StaticRouter } from 'react-router-dom';
import Main from '../../react/components/main';
import React from 'react';

const server_url = require('../constant/server_url')

/**
 * route的总入口，该函数处理所有get请求，调用getStore获取初始的state，使用state渲染html模版（SSR）。
 * @param ctx
 * @param next
 * @returns {Promise.<void>}
 * @constructor
 */
async function RootRouter(ctx, next) {
    console.log('request ' + ctx.path)

    let context = {};
    const store = getStore(ctx);
    const content = await getHtml(ctx, context, store);
    if (context.url) {
        //the math url uses <Redirect>
        ctx.redirect(context.url)
    } else {
        ctx.render('index_layout', {"title": 'Advanced Google Search Shortcuts' ,"content":content, "preloadedState":JSON.stringify(store.getState())});
    }
}

function getHtml(ctx, context, store) {
    return new Promise((resolve, reject) => {
        const content = ReactDOMServer.renderToString(
            <Provider store={store}>
                <StaticRouter
                    location={ctx.path}
                    context={context}>
                    <Main/>
                </StaticRouter>
            </Provider>
        );
        if (content)
            resolve(content)
    })
}

/**
 * 根据path返回相应的初始化state
 * @param ctx
 * @returns {*}
 */
function getStore(ctx) {
    switch (ctx.path) {
        case server_url.root:{
            return root()
        }
        case server_url.about:{
            return root()
        }
        case server_url.privacy:{
            return root()
        }
    }
}

module.exports = RootRouter;